#!/usr/bin/env perl

package generate;

use warnings;
use strict;

use lib './perl';
# JSON::Tiny is included in the "JSON" directory, so it doesn't need to be
# installed. JSON::Tiny is licensed under Artistic License version 2.0
# (http://www.perlfoundation.org/artistic_license_2_0) available from:
# https://metacpan.org/pod/JSON::Tiny
use JSON::Tiny qw(decode_json);

# For array_contains
use List::Util qw(any);

# Templating engine
use Text::Template;

sub get_file_contents {
	my $filepath = shift;
	if ( -f $filepath ) {	
		open( my $file_handle, "<", "$filepath" ) or die("File $filepath not found");
		$/ = undef;
		my $content = <$file_handle>;
		close($file_handle);
		return $content;
	} else {
		return '';
	}
}

# Get code from given filename.
# This also encodes *some* HTML entities for inclusion inside <pre> tags.
sub get_pre_code {
	my $code_text = get_file_contents(shift);
	$code_text =~ s/&/&amp;/g;
	$code_text =~ s/</&lt;/g;
	$code_text =~ s/>/&gt;/g;
	return $code_text;
}

sub write_file_contents {
	my $string = shift;
	my $filepath = shift;

	open(my $file_handler, '>', $filepath) or die $!;
	print $file_handler $string;
	close($file_handler);
}

sub read_json {
	return decode_json( get_file_contents(shift) );
}

sub string_replace {
	my $string = shift;
	my $search = shift;
	my $replace = shift;
	$string =~ s/\Q$search\E/$replace/g;
	return $string;
}

# requires having use List::Util qw(any);
sub array_contains {
	my $value = shift;
	# https://stackoverflow.com/a/16690762
	return any { $_ eq $value } @_;
}

my $json = read_json('src/info.json');

# Create template object
my $template = Text::Template->new(TYPE => 'FILE',  SOURCE => 'src/html/index.html');

# Attach default data to language entries according to default_langs
if ( $json->{languages} ) {
	foreach my $lang (@{$json->{languages}}) {
		if ( array_contains( $lang->{slug}, @{$json->{default_langs}} ) ) {
			$lang->{default} = 1;
		}
	}
}

# Get parsed template file
my $text = $template->fill_in(HASH => $json, DELIMITERS => [ '{_', '_}' ]);

# Write output
write_file_contents($text, 'public/index.html');
